var app = getApp()
Page({
  data: {
    orderId: '',
    orderDetail: {},
    checkedCode:[],
    max_refund:0,
    suggest_refund:0,
    refund_list:[],
    reason:'',
    contact:'',
    tid:'',
    toid:'',
    reasonList:["买错了/买多了","没时间消费","商家不接待","店内有更优惠活动","别的平台有更优惠的活动"],
    selectedReasons:[],
    explain:'',
  },
  onLoad: function (options) {
    this.setData({
      orderId: options.orderId
    })
  },
  reasonChange(e){
    this.data.selectedReasons = e.detail.value;
  },
  tkMoneyChange: function (e) {
    let {max_refund} = this.data
    console.log(e)
    if(e.detail.value<=max_refund) {
      console.log(1)
      this.setData({
        suggest_refund: e.detail.value
      })
    }else {
      console.log(2)
      this.setData({
        suggest_refund: max_refund
      })
      wx.showToast({
        title: '已超过最大金额',
        icon:'none'
      })
    }
    
  },
  tkReasonChange: function (e) {
    this.setData({
      explain: e.detail.value
    });
  
  },
  tkContactChange: function (e) {
    this.setData({
      contact: e.detail.value
    })
  },
  submitRefund: function () {
    var that = this;
    var data = {};
    data.map = 'applet_order_refund';
    data.tid = that.data.tid;
    data.money = that.data.suggest_refund;
    data.reason = that.data.selectedReasons.join("/");
    data.explain = that.data.explain;
    data.contact = that.data.contact;
    data.ticket_code = JSON.stringify(that.data.refund_list)
    console.log(data)
    console.log('that.data.suggest_refund',parseFloat(that.data.suggest_refund))
    if (data.money == "") {
      wx.showToast({
        title: "请输入退款金额",
        duration:2000,
        icon:"none"
      })
      return;
    }
    if (!(/^\d+(\.\d+)?$/.test(parseFloat(data.money)))) {
      wx.showToast({
        title: "请输入正确金额",
        duration:2000,
        icon:"none"
      })
      return;
    }
    if (parseFloat(data.money) > that.data.orderDetail.payment) {
      wx.showToast({
        title: "退款金额不能大于实际支付金额",
        duration:2000,
        icon:"none"
      })
      return;
    }
    if (data.reason == "") {

      wx.showToast({
        title: "请先选择退款原因",
        duration:2000,
        icon:"none"
      })
      return;
    }
    if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(data.contact)) {
      wx.showToast({
        title: "请输入正确的手机号",
        duration:2000,
        icon:"none"
      })
      return;
    }
    
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        wx.hideToast();
        if (res.data.ec == 200) {
          wx.showToast({
            title: '申请成功！',
            duration:2000
          })
          setTimeout(()=>{
            that.onShow();
          },2000)
          setTimeout(wx.navigateBack,2000)
        } else {
          wx.hideToast();
          wx.showToast({
            title: res.data.em,
            duration:2000,
            icon:"none"
          })
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var orderid = that.data.orderId;
    this.setData({
      tid: orderid
    })
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_order_detail',
        tid: orderid
      },
      success: function (res) {
        if (res.data.ec == 200) {
          var orderDetail = res.data.data
          let max_refund = 0
          let suggest_refund = 0
          // var refundAble = 0
          // orderDetail.goods.forEach(v => {
          //   if(v.ticket_info.wait_use){   //调试状态京东商品不存在这个属性
          //     refundAble += parseFloat(v.ticket_info.wait_use.max_refund)
          //   }
          // })
          // if (orderDetail.status == 3){
          //   refundAble += parseFloat(orderDetail.freight)
          // }
          console.log('orderDetail.source',orderDetail)
          if(orderDetail.postType=='3') {
            orderDetail.goods.map(val=>{
              if(val.ticket_info.wait_use) {
                val.ticket_info.wait_use.list.map(ticket=>{
                  let e={}
                  e.currentTarget={}
                  e.detail = {}
                  e.currentTarget.dataset = {
                    id:ticket.id, 
                    gid:val.gid, 
                    price:ticket.avg_price
                  }
                  e.detail.value = val.gid+'_'+ticket.id
                  that.checkboxChangeTicket(e)
                })
              }
            })
          }
          
          orderDetail.goods.map(val=>{
            if(val.ticket_info.wait_use) {
              val.ticket_info.wait_use.list.map(ticket=>{
                max_refund+=parseFloat(ticket.avg_price)
              })
            }
            if(val.ticket_info.length==0) {
              max_refund=parseFloat(orderDetail.total)
            }
            
          })
          
          if(orderDetail.source=="pft") {
            that.setData({
              suggest_refund:orderDetail.total
            })
          }
          if(orderDetail.freight!=='0.00') {
            max_refund+=parseFloat(orderDetail.freight)
            that.setData({
              suggest_refund:max_refund
            })
          }
          that.setData({
            orderDetail: res.data.data,
            max_refund
          })
          
          
          
          
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideToast();
      }
    });
  },

  checkboxChangeTicket:function(e){
    var { id, gid, price ,index} = e.currentTarget.dataset;
    var refund_list = this.data.refund_list
    var arr = [{ id: id, gid: gid, price: price }]
    var total = parseFloat(this.data.suggest_refund)
    if (refund_list.length == 0){
      var total = parseFloat(this.data.suggest_refund) + parseFloat(price)
      this.setData({
        suggest_refund: total,
        refund_list: arr
        })
    }else{
      var add = true;
      
      refund_list.forEach((v, index) => {
        if (v.id == id) {
          total=total - parseFloat(v.price) ;
          refund_list.splice(index, 1);
          this.setData({
            suggest_refund: total.toFixed(2),
            refund_list: refund_list
          })
          add = false
        }
      })
      if (add){
        total += parseFloat(price)
        this.setData({
          suggest_refund: total,
          refund_list: arr.concat(refund_list)
        })
      }
    }
    console.log(this.data.refund_list)
    this.setData({
      checkedCode:e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})